#include <iostream>
#include <string>
#include <functional>
#include <memory>
#include <unordered_map>
#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"

class TranslateServer
{
public:
    TranslateServer(int port)
        : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "TranslateServer", muduo::net::TcpServer::kNoReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::OnConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    // 启动
    void start()
    {
        _server.start();
        _baseloop.loop();
    }

private:
    // 建立连接后的回调
    // 只有在建立连接和断开连接才会被调用
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            std::cout << "建立链接:" << conn->name() << std::endl;
        }
        else
        {
            std::cout << "连接失败" << std::endl;
        }
    }

    static std::string translate(const std::string word)
    {
        std::unordered_map<std::string, std::string> dict{
            {"word", "单词"}, {"listen", "监听"}, {"message", "消息"}, {"apple", "苹果"}};

        auto iter = dict.find(word);
        if (iter != dict.end())
            return iter->second; // 找到翻译则立即返回
        
        return "没找到!";
    }
    // 业务处理
    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buffer, muduo::Timestamp timeout)
    {
        // 1.从buffer获取请求
        std::string inbuffer = buffer->retrieveAllAsString();
        // 2.处理业务
        if (inbuffer.back() == '\n')
            inbuffer.pop_back();
        std::string transl = TranslateServer::translate(inbuffer);
        // 3.发送响应
        conn->send(transl);
    }

private:
    muduo::net::TcpServer _server;
    muduo::net::EventLoop _baseloop;
};

int main()
{
    std::unique_ptr<TranslateServer> svr = std::make_unique<TranslateServer>(8080);
    svr->start();
}